<template>
  <div class="chat">
    <header class="page-header">
      <div class="container">
        <h1>AI 助手</h1>
        <p>与AI进行智能对话</p>
      </div>
    </header>

    <main class="container chat-container">
      <div class="model-select-container">
        <label for="model-select">选择模型：</label>
        <select id="model-select" v-model="selectedModel">
          <option v-for="model in availableModels" :key="model.value" :value="model.value">
            {{ model.label }}
          </option>
        </select>
      </div>

      <div class="messages" ref="messagesContainer">
        <div v-for="(message, index) in messages" :key="index" :class="['message', message.role]">
          <div class="message-content">
            <p v-html="formatMessage(message.content)"></p>
          </div>
        </div>
      </div>

      <div class="input-area">
        <div class="input-container">
          <textarea
            v-model="userInput"
            @keydown.enter.prevent="handleEnter"
            placeholder="输入您的问题..."
            rows="1"
            ref="inputArea"
          ></textarea>
          <button @click="sendMessage" :disabled="isLoading || !userInput.trim()">
            <span v-if="!isLoading">发送</span>
            <span v-else>请稍候...</span>
          </button>
        </div>
      </div>
    </main>
    <ImageGallery />
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch } from 'vue'
import { chatApi } from '@/api/api'
import { useUserStore } from '@/store/user'

const userStore = useUserStore()
const userInput = ref('')
const messages = ref([])
const isLoading = ref(false)
const messagesContainer = ref(null)
const inputArea = ref(null)
const isStreaming = ref(false)
const abortController = ref(null)

// 模型列表配置
const defaultModels = [
  { value: 'ollama', label: 'Ollama（默认模型 deepseek）' },
  { value: 'tongyi', label: '通义千问' },
  { value: 'hunyuan', label: '腾讯混元' },
  { value: 'doubao', label: '字节豆包' }
]

const availableModels = ref(defaultModels)
const selectedModel = ref('ollama')

// 自动调整输入框高度
const adjustTextareaHeight = () => {
  const textarea = inputArea.value
  if (textarea) {
    textarea.style.height = 'auto'
    textarea.style.height = `${Math.min(textarea.scrollHeight, 200)}px`
  }
}

// 滚动到最新消息
const scrollToBottom = async () => {
  await nextTick()
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 处理回车键发送消息
const handleEnter = (e) => {
  if (!e.shiftKey && !e.isComposing) {
    e.preventDefault()
    sendMessage()
  }
}

// 停止当前流式响应
const stopGeneration = () => {
  if (abortController.value) {
    abortController.value.abort()
    abortController.value = null
  }
  isStreaming.value = false
  isLoading.value = false
}

// 格式化消息内容（处理换行、链接等）
const formatMessage = (content) => {
  if (!content) return ''

  // 处理换行符
  let formatted = content.replace(/\n/g, '<br>')

  // 简单处理URL为可点击链接（安全注意：确保内容可信）
  formatted = formatted.replace(
    /(https?:\/\/[^\s]+)/g,
    '<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>'
  )

  return formatted
}

// 回调函数
const callbacks = {
  onMessage: (message) => {
    console.log('Received message:', message)

    // 找到 AI 消息对象
    const aiMessageIndex = messages.value.findIndex(m => m.isLoading === true)
    if (aiMessageIndex !== -1) {
      // 更新 AI 消息内容
      messages.value[aiMessageIndex].content += message.content || ''

      // 如果消息完成，标记加载状态为 false
      if (message.complete) {
        messages.value[aiMessageIndex].isLoading = false
        messages.value[aiMessageIndex].timestamp = new Date().toISOString()
      }

      // 滚动到底部
      scrollToBottom()
    }
  },
  onError: (error) => {
    console.error('Error:', error)

    // 找到 AI 消息对象，并设置错误信息
    const aiMessageIndex = messages.value.findIndex(m => m.isLoading === true)
    if (aiMessageIndex !== -1) {
      messages.value[aiMessageIndex].content = 'Error: ' + error.message
      messages.value[aiMessageIndex].isLoading = false
    }

    // 滚动到底部
    scrollToBottom()
  },
  onClose: () => {
    console.log('Connection closed')

    // 找到 AI 消息对象，并标记加载状态为 false
    const aiMessageIndex = messages.value.findIndex(m => m.isLoading === true)
    if (aiMessageIndex !== -1) {
      messages.value[aiMessageIndex].isLoading = false
    }

    // 滚动到底部
    scrollToBottom()
  }
}

// 发送消息到后端（流式版本）
const sendMessage = async () => {
  const message = userInput.value.trim()
  if (!message || isLoading.value) return

  // 添加用户消息
  messages.value.push({
    id: Date.now(),
    role: 'user',
    content: message,
    timestamp: new Date().toISOString()
  })

  // 添加AI占位消息
  const aiMessageId = Date.now() + 1
  messages.value.push({
    id: aiMessageId,
    role: 'assistant',
    content: '',
    isLoading: true,
    timestamp: new Date().toISOString()
  })

  userInput.value = ''
  isLoading.value = true
  isStreaming.value = true
  adjustTextareaHeight()
  await scrollToBottom()

  try {
    abortController.value = new AbortController()

    // 流式请求
    await chatApi.streamMessage(
      {
        user_id: userStore.userId || 'anonymous',
        userinput: message,
        modelname: selectedModel.value
      },
      callbacks
    )
  } catch (error) {
    console.error('Error:', error)

    // 找到 AI 消息对象，并设置错误信息
    const aiMessageIndex = messages.value.findIndex(m => m.isLoading === true)
    if (aiMessageIndex !== -1) {
      messages.value[aiMessageIndex].content = 'Error: ' + error.message
      messages.value[aiMessageIndex].isLoading = false
    }

    // 滚动到底部
    scrollToBottom()
  } finally {
    isLoading.value = false
    isStreaming.value = false
  }
}

// 初始化
onMounted(async () => {
  // 添加欢迎消息
  messages.value.push({
    id: Date.now(),
    role: 'assistant',
    content: `你好！我是AI助手，当前使用模型：${
      availableModels.value.find(m => m.value === selectedModel.value)?.label || selectedModel.value
    }。有什么我可以帮你的吗？`,
    timestamp: new Date().toISOString()
  })
  await scrollToBottom()
})

// 监听模型切换
watch(selectedModel, (newModel) => {
  messages.value.push({
    id: Date.now(),
    role: 'assistant',
    content: `已切换到模型：${availableModels.value.find(m => m.value === newModel)?.label || newModel}`,
    timestamp: new Date().toISOString()
  })
  scrollToBottom()
})
</script>

<style scoped>
.page-header {
  background: linear-gradient(120deg, rgba(44, 62, 80, 0.9), rgba(52, 152, 219, 0.9)), url('@/assets/img/post-bg.jpg');
  background-blend-mode: overlay;
  color: white;
  padding: 3rem 0;
  text-align: center;
  margin-bottom: 2rem;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  border-radius: 0 0 30px 30px;
}

.chat-container {
  max-width: 900px;
  margin: 0 auto;
  padding: 0 1.5rem;
  display: flex;
  flex-direction: column;
  height: calc(100vh - 280px);
}

/* 模型选择样式 */
.model-select-container {
  margin-bottom: 1rem;
  display: flex;
  align-items: center;
  gap: 0.8rem;
}

.model-select-container label {
  font-size: 1rem;
  color: #333;
}

.model-select-container select {
  padding: 0.5rem 1rem;
  font-size: 1rem;
  border-radius: 12px;
  border: none;
  background-color: #f8f9fa;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.model-select-container select:hover,
.model-select-container select:focus {
  background-color: white;
  outline: none;
}

.messages {
  flex: 1;
  overflow-y: auto;
  padding: 1.5rem;
  background-color: rgba(248, 249, 250, 0.9);
  border-radius: 16px;
  margin-bottom: 1.5rem;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.message {
  margin-bottom: 1.5rem;
  display: flex;
  flex-direction: column;
}

.message.user {
  align-items: flex-end;
}

.message.assistant {
  align-items: flex-start;
}

.message-content {
  max-width: 75%;
  padding: 1rem 1.2rem;
  border-radius: 18px;
  word-break: break-word;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  line-height: 1.5;
}

.user .message-content {
  background: linear-gradient(120deg, #007bff, #0056b3);
  color: white;
}

.assistant .message-content {
  background-color: white;
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.input-area {
  padding: 1.2rem 0;
}

.input-container {
  display: flex;
  gap: 0.8rem;
  background-color: white;
  border: none;
  border-radius: 16px;
  padding: 0.8rem;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

textarea {
  flex: 1;
  border: none;
  resize: none;
  padding: 0.8rem;
  font-size: 1rem;
  max-height: 150px;
  outline: none;
  border-radius: 12px;
  background-color: #f8f9fa;
  transition: background-color 0.3s ease;
}

textarea:focus {
  background-color: white;
}

button {
  padding: 0.8rem 1.5rem;
  background: linear-gradient(120deg, #007bff, #0056b3);
  color: white;
  border: none;
  border-radius: 12px;
  cursor: pointer;
  white-space: nowrap;
  font-weight: 500;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

button:disabled {
  background: linear-gradient(120deg, #6c757d, #495057);
  cursor: not-allowed;
  transform: none;
}

button:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}
</style>